<?php

/**
 * login actions.
 *
 * @package    toyomotor
 * @subpackage login
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class loginActions extends sfActions
{
 /**
  * Executes index action
  *
  * @param sfRequest $request A request object
  */
  public function executeIndex(sfWebRequest $request)
  {
      
      if( $this->getUser()->isAuthenticated() ){
          
          $this->redirect('citaadmin/index');
          
      }
    
  }
  
  /**
   * Metodo para recibir el formulario de login y revisar si puede entrar o no
   * @param sfWebRequest $request 
   */
  public function executeSesion(sfWebRequest $request){
        $email = $this->request->getParameter('email');
        $password = md5($this->request->getParameter('password'));
        $usuarios = Doctrine_Core::getTable('Usuario')->createQuery('u')
                        ->where('u.email = ?', $email)
                        ->andWhere('u.password = ?', $password)
                        ->andWhere('(u.perfil = 1 OR u.perfil = 2)');

        $query = $usuarios->fetchOne();
        
        if(!$query){
            
            $this->redirect('@homepage');
            
        }else{
            
            switch ($query->getPerfil())
              {
                case "1":
                    $credential = "Admin";
                    break;
                case "2":
                    $credential = "Asesor";
                    break;
                default:
                    $this->redirect('@homepage');
                    break;
              }
            
            $this->getUser()->setAuthenticated(true);
            $this->getUser()->addCredential($credential);
            $this->getUser()->setAttribute('nombre', $query->getNombre());
            $this->getUser()->setAttribute('id_usuario',$query->getIdUsuario());
            
            $this->redirect('citaadmin/index');

        }     
      
  }
  
  /**
   * Metodo para cerrar la sesion
   * @param sfWebRequest $request 
   */
  public function executeCerrarsesion(sfWebRequest $request){
      
    $this->getUser()->setAuthenticated(false);

    $this->getUser()->clearCredentials();

    $this->getUser()->getAttributeHolder()->removeNamespace('Admin');

    $this->getUser()->getAttributeHolder()->remove('id_usuario');
    $this->getUser()->getAttributeHolder()->remove('nombre');

    $this->getUser()->shutdown();

    $this->redirect('@homepage');
      
  }
  
}
